/**
 * @author erond
 */

package slave;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Vector;

import javax.bluetooth.BluetoothStateException;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
import com.intel.bluetooth.BlueCoveImpl;
import commonUtility.NetworkInterfaceIP;


/**
 * This code was edited or generated using CloudGarden's Jigloo
 * SWT/Swing GUI Builder, which is free for non-commercial
 * use. If Jigloo is being used commercially (ie, by a corporation,
 * company or business for any purpose whatever) then you
 * should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details.
 * Use of Jigloo implies acceptance of these licensing terms.
 * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
 * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
 * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
 */

/**
 * Interfaccia per il settaggio dei parametri di bootstrap dell'entità SLAVE
 */
public class SlaveSetting extends javax.swing.JFrame implements Runnable {

	{
		//Set Look & Feel   
		try {
			javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	private static final long serialVersionUID = 8679774994733884227L;
	private JPanel jPanel1;
	private JLabel jLabelSlaveLogo;
	private JButton jButtonStart;
	private NetworkInterfaceIP netI;
	

	/**
	 * @return the jButtonStart
	 */
	public JButton getjButtonStart() {
		return jButtonStart;
	}

	private Slave slave = null;
	private JComboBox networkCombo;
	private JLabel jNEt;
	private JPanel jPanel4;
	private JLabel jLabel8;
	private JSeparator jSeparator1;
	private JLabel jLabel7;
	private JTextField weightRSSI;
	private JLabel jLabel6;
	private JTextField weightClient;
	private JLabel jLabel5;
	private JComboBox helperDeviceCombo;
	private JComboBox mainDeviceCombo;
	private JLabel jLabel4;
	private JTextField jTextField_portaDeleteAfter;
	private JLabel jLabel_portaDeleteAfter;
	private JTextField jTextField_DeletePortBefore;
	private JLabel jLabel_portaDeleteBefore;
	private JTextField jTextField_portaJob;
	private JLabel jLabel_portaJob;
	private JTextField jTextField_MulticastPort;
	private JLabel jLabel_MulticastPort;
	private JPanel jPanel_left;
	private JLabel jLabel3;
	private JLabel jLabel2;
	private JLabel jLabel1;
	private JPanel jPanel3;
	private JTextField jTextField_MulticastIP;
	private JLabel jLabel_SlaveMulticastIP;
	private JTextField jTextField_MasterIP;
	private JLabel jLabel_MasterIP;
	private JPanel jPanel_Right;
	private JPanel jPanel2;
	private JLabel copyright;

	public void setSlave(Slave s) {
		slave=s;
	}

	public Slave getSlave() {
		return slave;
	}

	/**
	 * Auto-generated main method to display this JFrame
	 */
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				SlaveSetting inst = new SlaveSetting("Slave bootstrap setting",null);
				inst.setLocationRelativeTo(null);
				inst.setVisible(true);
			}
		});
	}

	/**
	 * @param name Nome dell'interfaccia grafica
	 * @param s Riferimento al thread principale che avvierà le varie parti del sistema
	 */
	public SlaveSetting(String name, Slave s) {
		super(name);
		setName(name);
		initGUI();
		getNetInterface();
		getDevice();
		setSlave(s);
		slaveReset();
	}

	public void run() {
		SlaveSetting inst = new SlaveSetting("Slave bootstrap setting",getSlave());
		inst.setLocationRelativeTo(null);
		inst.setVisible(true);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	private void initGUI() {
		try {
			ImageIcon image = new ImageIcon("./media/device.png");
			setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
			{
				jPanel1 = new JPanel();
				jPanel1.setLayout(null);
				getContentPane().add(getJPanel1(), BorderLayout.CENTER);
				jPanel1.setBackground(new java.awt.Color(214,216,222));
				jPanel1.setPreferredSize(new java.awt.Dimension(413, 499));
				jPanel1.setName("Slave bootstrap setting");

				//Logo slave
				ImageIcon masterLogo = new ImageIcon("./media/slave.png");
				jLabelSlaveLogo = new JLabel();
				jLabelSlaveLogo.setIcon(masterLogo);
				jLabelSlaveLogo.setBounds(50, 6, 323, 90);
				jPanel1.add(jLabelSlaveLogo);

				//Pulsante START
				jButtonStart = new JButton("START");
				jButtonStart.setBounds(139, 421, 133, 45);
				jButtonStart.setFont(new java.awt.Font("AlArabiya",1,14));
				jPanel1.add(jButtonStart);
				jButtonStart.addMouseListener(new MouseAdapter() {
					public void mouseClicked(MouseEvent evt) {
						jButtonStartMouseClicked(evt);
						
					}
				});

				//Copyright
				copyright = new JLabel();
				jPanel1.add(copyright);
				copyright.setText("Coluccio-Di Mango-Ciavarella Copyright ©2009 - all rights reserved");
				copyright.setHorizontalAlignment(SwingConstants.CENTER);
				copyright.setFont(new java.awt.Font("AlArabiya",1,8));
				copyright.setEnabled(false);
				copyright.setBounds(83, 478, 241, 10);
				{
					jPanel2 = new JPanel();
					jPanel1.add(getJPanel2());
					jPanel2.setBounds(6, 105, 405, 309);
					jPanel2.setBorder(BorderFactory.createTitledBorder(""));
					jPanel2.setLayout(null);
					{
						jPanel_left = new JPanel();
						FlowLayout jPanel_leftLayout = new FlowLayout();
						jPanel2.add(getJPanel_left());
						jPanel_left.setLayout(jPanel_leftLayout);
						jPanel_left.setBounds(9, 7, 182, 94);
						{
							jLabel_MasterIP = new JLabel();
							jPanel_left.add(getJLabel_MasterIP());
							jLabel_MasterIP.setText("Master IP");
						}
						{
							jTextField_MasterIP = new JTextField();
							jPanel_left.add(getJTextField_MasterIP());
							jTextField_MasterIP.setText("localhost");
							jTextField_MasterIP.setPreferredSize(new java.awt.Dimension(99, 27));
							jTextField_MasterIP.setHorizontalAlignment(SwingConstants.CENTER);
						}
						{
							jLabel_SlaveMulticastIP = new JLabel();
							jPanel_left.add(getJLabel_SlaveMulticastIP());
							jLabel_SlaveMulticastIP.setText("Xml Multicast IP");
						}
						{
							jTextField_MulticastIP = new JTextField();
							jPanel_left.add(getJTextField_MulticastIP());
							jTextField_MulticastIP.setText("230.0.0.2");
						}
						{
							jLabel_MulticastPort = new JLabel();
							jPanel_left.add(jLabel_MulticastPort);
							jLabel_MulticastPort.setText("Xml Multicast PORT");
						}
						{
							jTextField_MulticastPort = new JTextField();
							jPanel_left.add(getJTextField_MulticastPort());
							jTextField_MulticastPort.setText("65432");
						}
					}
					{
						jPanel_Right = new JPanel();
						jPanel2.add(getJPanel_Right());
						jPanel_Right.setBounds(191, 7, 202, 94);
						{
							jLabel_portaJob = new JLabel();
							jPanel_Right.add(jLabel_portaJob);
							jLabel_portaJob.setText("Master Job Server Port");
						}
						{
							jTextField_portaJob = new JTextField();
							jPanel_Right.add(getJTextField_portaJob());
							jTextField_portaJob.setText("20000");
						}
						{
							jLabel_portaDeleteBefore = new JLabel();
							jPanel_Right.add(jLabel_portaDeleteBefore);
							jLabel_portaDeleteBefore.setText("Delete Port Before");
						}
						{
							jTextField_DeletePortBefore = new JTextField();
							jPanel_Right.add(getJTextField_DeletePortBefore());
							jTextField_DeletePortBefore.setText("30001");
						}
						{
							jLabel_portaDeleteAfter = new JLabel();
							jPanel_Right.add(jLabel_portaDeleteAfter);
							jLabel_portaDeleteAfter.setText("Delete Port After");
						}
						{
							jTextField_portaDeleteAfter = new JTextField();
							jPanel_Right.add(getJTextField_portaDeleteAfter());
							jTextField_portaDeleteAfter.setText("30002");
						}
					}
					{
						jPanel3 = new JPanel();
						jPanel2.add(getJPanel3());
						jPanel3.setBounds(7, 156, 384, 139);
						jPanel3.setLayout(null);
						{
							jLabel1 = new JLabel(image);
							jPanel3.add(getJLabel1());
							jLabel1.setBounds(56, 18, 59, 82);
						}
						{
							jLabel2 = new JLabel();
							jPanel3.add(getJLabel2());
							jLabel2.setText("Select local bluetooth device for trasmission:");
							jLabel2.setBounds(48, -8, 320, 27);
							jLabel2.setFont(new java.awt.Font("AlArabiya",1,12));
						}
						{
							jLabel3 = new JLabel();
							jPanel3.add(getJLabel3());
							jLabel3.setText("HELPER DEVICE");
							jLabel3.setBounds(155, 61, 109, 15);
						}
						{
							jLabel4 = new JLabel();
							jPanel3.add(getJLabel4());
							jLabel4.setText("MAIN DEVICE");
							jLabel4.setBounds(155, 34, 115, 15);
						}
						{
							ComboBoxModel jComboBox1Model = 
								new DefaultComboBoxModel();
							mainDeviceCombo = new JComboBox();
							jPanel3.add(getJComboBox1());
							mainDeviceCombo.setModel(jComboBox1Model);
							mainDeviceCombo.setBounds(269, 32, 89, 18);
						}
						{
							ComboBoxModel jComboBox2Model = 
								new DefaultComboBoxModel();
							helperDeviceCombo = new JComboBox();
							jPanel3.add(helperDeviceCombo);
							helperDeviceCombo.setModel(jComboBox2Model);
							helperDeviceCombo.setBounds(269, 59, 89, 18);
						}
						{
							jLabel5 = new JLabel();
							jPanel3.add(jLabel5);
							jLabel5.setText("Weight Clients");
							jLabel5.setBounds(154, 89, 103, 27);
						}
						{
							weightClient = new JTextField();
							jPanel3.add(getJTextField1());
							weightClient.setText("0.5");
							weightClient.setBounds(277, 84, 80, 27);
						}
						{
							jLabel6 = new JLabel();
							jPanel3.add(jLabel6);
							jLabel6.setText("Weight RSSI");
							jLabel6.setBounds(154, 110, 80, 27);
						}
						{
							weightRSSI = new JTextField();
							jPanel3.add(getJTextField2());
							weightRSSI.setText("0.5");
							weightRSSI.setBounds(277, 110, 80, 27);
						}
						{
							jLabel7 = new JLabel();
							jPanel3.add(getJLabel7());
							jLabel7.setText("Lambda function");
							jLabel7.setBounds(30, 99, 111, 27);
						}
						{
							jLabel8 = new JLabel();
							jPanel3.add(jLabel8);
							jLabel8.setText("{");
							jLabel8.setBounds(139, 73, 9, 74);
							jLabel8.setFont(new java.awt.Font("AlArabiya",0,26));
						}
					}
					{
						jSeparator1 = new JSeparator();
						jPanel2.add(jSeparator1);
						jSeparator1.setBounds(44, 143, 317, 7);
					}
					{
						jPanel4 = new JPanel();
						jPanel2.add(jPanel4);
						jPanel4.setBounds(14, 108, 377, 24);
						{
							jNEt = new JLabel();
							jPanel4.add(jNEt);
							jNEt.setText("Choose NETWORK interface:");
							jNEt.setPreferredSize(new java.awt.Dimension(183, 15));
						}
						{
							ComboBoxModel networkComboModel = 
								new DefaultComboBoxModel();
							networkCombo = new JComboBox();
							jPanel4.add(networkCombo);
							networkCombo.setModel(networkComboModel);
							networkCombo.setPreferredSize(new java.awt.Dimension(89, 21));
						}
					}
				}

			}
			pack();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@SuppressWarnings("unchecked")
	public void getDevice(){
		try {
			Vector device = BlueCoveImpl.getLocalDevicesID();
			BlueCoveImpl.shutdown();
			device.size();
			for(int i=0;i<device.size();i++){
			mainDeviceCombo.addItem(device.elementAt(i));
			helperDeviceCombo.addItem(device.elementAt(i));
			}
			
		} catch (BluetoothStateException e) {
			e.printStackTrace();
		}	
			
		}		
	
	
	public void getNetInterface(){
		netI = new NetworkInterfaceIP();
		try {
		   Enumeration<NetworkInterface> net = netI.getAvailableNetworkInterfaces();
		   while (net.hasMoreElements()){
				String name = 	net.nextElement().getDisplayName();
				networkCombo.addItem(name);
				}		
		} catch (Exception e) {
			e.printStackTrace();
		}	
			
		}		
	
	
	/**
	 * Evento pressione pulsante START
	 * @param evt
	 */
	private void jButtonStartMouseClicked(MouseEvent evt) {
		{//Setting BT device
		BluetoothStack.getInstance().setMain((String) mainDeviceCombo.getSelectedItem());
		BluetoothStack.getInstance().setHelper((String) helperDeviceCombo.getSelectedItem());
		}
		
		{
		String net = (String)networkCombo.getSelectedItem();	
		slave.setNetwork(net);
		}
		{//Setting lambda
		String wc = weightClient.getText();
		Double wcd = Double.parseDouble(wc);	
		String wr = weightRSSI.getText();
		Double wrd = Double.parseDouble(wr);
		slave.setWeightC(wcd);
		slave.setWeightRSSI(wrd);
		}
	
		
		//Retrieving Textfield data and setting slave field
		InetAddress masterIP = null;
		try {
			masterIP = InetAddress.getByName(getJTextField_MasterIP().getText());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		getSlave().setMasterIP(masterIP);
		
		InetAddress multicastIP = null;
		try {
			multicastIP = InetAddress.getByName(getJTextField_MulticastIP().getText());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
		getSlave().setMulticastIP(multicastIP);
		
		int multicastPort;
		multicastPort=Integer.parseInt(getJTextField_MulticastPort().getText());
		getSlave().setMulticastPort(multicastPort);
		
		int portaJob;
		portaJob=Integer.parseInt(getJTextField_portaJob().getText());
		getSlave().setPortaJob(portaJob);
		
		int portaDelete_before;
		portaDelete_before=Integer.parseInt(getJTextField_DeletePortBefore().getText());
		getSlave().setPortaDelete_before(portaDelete_before);
		
		int portaDelete_after;
		portaDelete_after=Integer.parseInt(getJTextField_portaDeleteAfter().getText());
		getSlave().setPortaDelete_after(portaDelete_after);
		
		//Esco
		this.setVisible(false);
		this.dispose();
		synchronized (getSlave().getSemaphore()) {
			getSlave().getSemaphore().notify();
		}
		
	}//fine evento pressio tasto START

	public JPanel getJPanel1() {
		return jPanel1;
	}
	
	public JPanel getJPanel2() {
		return jPanel2;
	}
	
	public JPanel getJPanel_left() {
		return jPanel_left;
	}
	
	public JPanel getJPanel_Right() {
		return jPanel_Right;
	}
	
	public JLabel getJLabel_MasterIP() {
		return jLabel_MasterIP;
	}
	
	public JTextField getJTextField_MasterIP() {
		return jTextField_MasterIP;
	}
	
	public JLabel getJLabel_SlaveMulticastIP() {
		return jLabel_SlaveMulticastIP;
	}
	
	public JTextField getJTextField_MulticastIP() {
		return jTextField_MulticastIP;
	}
	
	public JTextField getJTextField_MulticastPort() {
		return jTextField_MulticastPort;
	}
	
	public JTextField getJTextField_portaJob() {
		return jTextField_portaJob;
	}
	
	public JTextField getJTextField_DeletePortBefore() {
		return jTextField_DeletePortBefore;
	}
	
	public JTextField getJTextField_portaDeleteAfter() {
		return jTextField_portaDeleteAfter;
	}
	
	public JPanel getJPanel3() {
		return jPanel3;
	}
	
	public JLabel getJLabel1() {
		return jLabel1;
	}
	
	public JLabel getJLabel2() {
		return jLabel2;
	}
	
	public JLabel getJLabel3() {
		return jLabel3;
	}
	
	public JLabel getJLabel4() {
		return jLabel4;
	}
	
	public JComboBox getJComboBox1() {
		return mainDeviceCombo;
	}
	
	public JTextField getJTextField1() {
		return weightClient;
	}
	
	public JTextField getJTextField2() {
		return weightRSSI;
	}
	
	public JLabel getJLabel7() {
		return jLabel7;
	}
	
	/**
	 * Metodo per la copia a byte di un file
	 * @param src Path completo del file sorgente
	 * @param dst Path completo del file destinazione
	 * @throws IOException
	 */
	public void copyFile(File src, File dst) throws IOException {

		InputStream in = new FileInputStream(src);		   
		OutputStream out = new FileOutputStream(dst);

		byte[] buf = new byte[1024];
		int len;
		while ((len = in.read(buf)) > 0) {
			out.write(buf, 0, len);
		}
		in.close();
		out.close();
	}


	/**
	 * Metodo per la copia dell'intero contenuto di una directory in un'altra
	 * @param sDir Path completo della directory sorgente
	 * @param dDir Path completo della directory destinazione
	 * @throws IOException
	 */
	public void copyDirectory(String sDir, String dDir) throws IOException{
		File srcDir = new File(sDir);
		File dstDir = new File(dDir);
		if (srcDir.isDirectory()) {
			if (!dstDir.exists()) {
				dstDir.mkdir();
			}
			String[] children = srcDir.list();
			for (int i=0; i<children.length; i++) {
				if (!children[i].contains("svn")) {
					copyDirectory(sDir+"/"+children[i], dDir+"/"+children[i]);
				}
			}
		} else {
			copyFile(srcDir, dstDir);
		}
	}

	/**
	 * Metodo che svuolta una directory da tutti i file e sottodirectory contenuti/e
	 * @param srcDir Path completo della directory da svuotare
	 * @throws IOException
	 */
	public void cleanDir(String srcDir) throws IOException {
		File dir = new File(srcDir);
		if (dir.isDirectory()) {
			if (dir.exists()) {
				String[] children = dir.list();
				for (int i=0; i<children.length; i++) {
					File toDelete = new File(dir+"/"+children[i]);
					toDelete.delete();
				}
			}
		}
	}
	
	/**
	 * Metodo per il reset dei file di sistema
	 */
	private void slaveReset() {
		
			//svuoto la cartella slaveTmp
			try {
				cleanDir("./slaveTmp");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			//copio i file che servono all'inizio all'interno di slaveTmp
			try {
				copyDirectory("./slave_reset/slaveTmp", "./slaveTmp");
			} catch (IOException e) {
				e.printStackTrace();
			}
			//svuoto la cartella xml
			try {
				cleanDir("./xml");
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			//copio i file che servono all'inizio all'interno di xml
			try {
				copyDirectory("./slave_reset/xml", "./xml");
			} catch (IOException e) {
				e.printStackTrace();
			}
		} 
}
